#include <string.h>
#include <iostream>

using std::cout;
using std::endl;

class Computer
{
public:
    Computer(){ 
        cout << "Computer()" << endl;   
        _brand = nullptr;//本质上是赋值语句
        _price = 0;
    }

    Computer(const char * brand, double price)
    {
        cout << "Computer(const char*, double)" << endl;
        //开辟的是堆空间的字符串
        _brand = new char[strlen(brand) + 1]();
        strcpy(_brand, brand);
        _price = price;
    }

    //系统提供的拷贝构造函数 不再满足需求,造成了double free的问题
    /* Computer(const Computer& rhs) */  
    /* : _brand(rhs._brand) //指针的复制,传递的是地址 */
    /* , _price(rhs._price) */
    /* { */
    /*     cout << "Computer(const Computer &)" << endl; */
    /* } */

    Computer(const Computer & rhs)
    : _brand(new char[strlen(rhs._brand) + 1]())
    , _price(rhs._price)
    {
        cout << "Computer(const Computer &)" << endl;
        strcpy(_brand, rhs._brand);
    }


    //系统提供的默认的析构函数 不再满足需求
    /* ~Computer() */
    /* {   cout << "~Computer()" << endl;  } */

    //对象的生命周期结束时，一定会自动调用析构函数
    ~Computer()
    {   
        cout << "~Computer()" << endl;  
        if(_brand) {
            delete [] _brand;//回收一个数组
            _brand = nullptr;
        }
    }

    void print() 
    {
        if(_brand) {
            cout << "brand:" << _brand << endl;
            cout << "price:" << _price << endl;
        }
    }

private:
    char * _brand;//64位系统一个指针占据的空间是8个字节
    double _price;
};

int main()
{
    Computer c1("Huawei", 6666);
    cout << "c1:" << endl;
    c1.print();
    cout << endl;

    //Computer c2(c1);
    Computer c2 = c1;
    cout << "c2:" << endl;
    c2.print();

    cout << "----" << endl;

    return 0;
}

